﻿using System;
using System.Linq;
using System.Threading.Tasks;
using DotNetCore.CAP;
using Microsoft.Extensions.Configuration;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.RecurringJobs.Dto;
using SqlSugar;

namespace NP.BPMReportPlatform.RecurringJobs
{
    public class LCZXRZXQGLRecurringJob : BpmReportPlatformRecurringJob, ILCZXRZXQGLRecurringJob
    {
        // 获取所有流程编号

        private readonly SqlSugarClient _db, _dbPlatform;

        private string urlTemplate = "";

        private ICapPublisher _capBus;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sqlSugarAppService"></param>
        public LCZXRZXQGLRecurringJob(ISqlSugarAppService sqlSugarAppService, ICapPublisher publisher,IConfiguration configuration)
        {
            urlTemplate = configuration["Nippon:LCZXRZXQGL:template"];
            _capBus = publisher;
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
         
        }


        public async Task SendEmailByExpiredCertificateNumber()
        {
            // 获取所有即将过期 的证书

            // 当前时间
            var date = DateTime.Now;
            // 6个月后 必须使用天数 
            var halfDate = date.AddDays(180);
            // 3个月后
            var thirdDate = date.AddDays(90);

            var expiredCerts = await _db.Queryable<LCZXRZXQGLDetail>()
                .Where(x =>
                    x.CertificateDate != null &&
                    // 半年
                    ((x.CertificateDate.Value.Year == halfDate.Year
                      && x.CertificateDate.Value.Month == halfDate.Month
                      && x.CertificateDate.Value.Day == halfDate.Day)
                        ||
                        // 3个月
                        (x.CertificateDate.Value.Year == thirdDate.Year
                              && x.CertificateDate.Value.Month == thirdDate.Month
                              && x.CertificateDate.Value.Day == thirdDate.Day))

                    ).ToListAsync();

            var ids = expiredCerts.Select(x => x.InstanceNumber).Distinct();

            // 获取主体信息
            var certHeader = await _db.Queryable<LCZXRZXQGLHeader>()
                .Where(x => ids.Contains(x.InstanceNumber)).ToListAsync();


            // 获取发起人信息，并拼接到模型中
            var userIds = certHeader.Select(x => x.AddUserId).Distinct();

            var users = await _dbPlatform.Queryable<Users>().Where(x => userIds.Contains(x.UserId)).ToListAsync();

            var userWorkNumbers = users.Select(x => x.WorkNumber);

            var userExtension = await _dbPlatform.Queryable<UserExtension>()
                .Where(x => userWorkNumbers.Contains(x.Sapemployeeid)).ToListAsync();
            // 获取BOSS
            var bossWorkNumbers = userExtension.Select(x => x.Bossemployeeid).Distinct();

            // 查询到领导信息
            var bossUsers = await _dbPlatform.Queryable<Users>().Where(x => bossWorkNumbers.Contains(x.WorkNumber))
                .ToListAsync();


            foreach (var header in certHeader)
            {
                // 获取发起人
                var user = users.FirstOrDefault(x => x.UserId == header.AddUserId);
                Users bossUser = null;
                if (user != null)
                {
                    // 获取 发起人上级
                    var userDetail = userExtension.FirstOrDefault(x => x.Sapemployeeid == user.WorkNumber);
                    if (userDetail != null)
                    {
                        // 获取用户上级
                        bossUser = bossUsers.FirstOrDefault(x => userDetail.Bossemployeeid == x.WorkNumber);
                    }
                }

                var emailAddress = "";

                if (bossUser == null && user == null)
                {
                    continue;
                }


                if (bossUser != null)
                {
                    emailAddress += bossUser.Email + ";";
                }

                if (user != null)
                {
                    emailAddress += user.Email + ";";
                }

                var count = expiredCerts.Count(x => x.InstanceNumber == header.InstanceNumber);

                var topic = $"[通知] 立才中心认证信息过期提醒，来自BPM系统，流程编号{header.InstanceNumber}";

                var newUrl = urlTemplate.Replace("{str}", header.InstanceNumber);

                var content = $"您好，{header.TrainSchool}学校有{count}名学员的认证信息即将过期，请<a href='{newUrl}'>点击查看详情<a/>";

                await _capBus.PublishAsync(
                    "bpmnew.EmailAppService.SendEmailAsync",
                    new SendEmailSimpleDto()
                    {
                        To = emailAddress,
                        Subject = topic,
                        Body = content,
                        InstanceNumber = header.InstanceNumber
                    });
            }
        }
    }
}